import { message } from 'antd';

const beforeUpload = (file, callback) => {
    // const isJPG = file.type === 'image/jpeg';
    const isJPG = (["image/jpg", "image/jpeg", "image/png", "image/pjpeg", "image/gif", "image/bmp", "image/x-png"]).findIndex(itm => file.type == itm);
    if (!(isJPG > -1)) {
        message.error('You can only upload JPG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return new Promise((resolve, reject) => {
        util.getBase64(file, (imageUrl) => {
            if (typeof (callback) == 'function') {
                callback(imageUrl);
            }
            resolve();
        })
    })
}

const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}

export const util = {
    beforeUpload,
    getBase64
};